/*

Input: newdata/estimation_prep_ltw18 [prepared precinct-level panel]

Output:
	- Figures 1, D.3, D.5, D.6
	
Tasks: Descriptives at the precinct level
	
	
	
*/	

* PULL: precinct-level panel
	use "$newdata/estimation_prep_ltw18.dta", clear
	
	
********************************************************************************
* Prep
		
	xtset sb_new wahl_id	

	// english labels
	label define wahl_id 1 "State (2013)", modify
	label define wahl_id 2 "Federal (2013)", modify
	label define wahl_id 3 "Municipal (2014)", modify
	label define wahl_id 4 "European (2014)", modify
	label define wahl_id 5 "Federal (2017)", modify
	label define wahl_id 6 "State (2018)", modify
	label define wahl_id 7 "European (2019)", modify
	label define wahl_id 8 "Municipal (2020)", modify
		

	* gen wahl_date := Election date
	gen 	wahl_date = mdy(9,27,2009) if wahl_id == 0
	replace wahl_date = mdy(9,15,2013) if wahl_id == 1
	replace	wahl_date = mdy(9,22,2013) if wahl_id == 2
	replace	wahl_date = mdy(3,16,2014) if wahl_id == 3
	replace	wahl_date = mdy(5,25,2014) if wahl_id == 4
	replace	wahl_date = mdy(9,24,2017) if wahl_id == 5
	replace	wahl_date = mdy(10,14,2018) if wahl_id == 6	
	replace	wahl_date = mdy(5,26,2019) if wahl_id == 7
	replace	wahl_date = mdy(3,15,2020) if wahl_id == 8
	
	format wahl_date %d 


* mean of outcomes, weighted by #eligible voters
	su turnout_tot_req turnout_urne turnout_pos_req [aw=wahlber_gesamt]

	
	* PLOT: FIGURE D3. Distribution of Precinct Size
* FIG: Distribution of UNHARMONIZED precinct sizes
frame copy default tmp, replace
frame tmp {
	// pull UNCONVERTED, NON-HARMONIZED data
	use "$newdata/raw_stimmbez_full.dta", clear
	
	su wahlber_gesamt, det	
	sum wahlber_gesamt if  inlist(wahl,"BTW17", "LTW18", "EUW19", "KOW20"), d
	sum wahlber_gesamt if  !inlist(wahl,"BTW17", "LTW18", "EUW19", "KOW20"), d
	bys wahl: su wahlber_gesamt ew_ges

	// Density Plot: Precinct sizes over all elections
	su wahlber_gesamt, det
	local p50 = r(p50)
	tw (hist wahlber_gesamt, fcol(%0)),  ytitle("Density") xtitle("Precinct size (# eligible voters)") ///
		legend(off) aspect(.7) xline(`p50', lcol(maroon) lpat(solid)) name(overall, replace)

	// Density Plot: Precinct sizes over all elections
	tw (hist wahlber_gesamt if inlist(wahl,"BTW17", "LTW18", "EUW19", "KOW20"), fcol(%0)) ///
		(hist wahlber_gesamt if  !inlist(wahl,"BTW17", "LTW18", "EUW19", "KOW20"), fcol(%50)) ///
		, ytitle("Density")  xtitle("Precinct size (# eligible voters)") ///
		legend(lab(1 "After 2017") lab(2 "Before 2017") ring(0) pos(10)) aspect(.7) name(split, replace)
		
		
	graph combine overall split, 	xcommon ycommon imargin(0 1 0 0)
	graph export "$figures/Figure_D3_nbr_eligible_voters_stimmbez.pdf", replace
}	
	
	
* Figure: Turnout and #EV over time
frame copy default tmp, replace
frame tmp {
	
	* AGGREGATE to city level (checked: aggregation matches city-level official stats)	
	bys wahl_id stadtbez: egen sbez_wahlber_gesamt = total(wahlber_gesamt)
	duplicates drop stadtbez wahl_id, force
	collapse (rawsum)  wahlber_gesamt=sbez_wahlber_gesamt (mean) sbez_turnout* [pw=sbez_wahlber_gesamt], by(wahl_date wahl wahl_type)

	// rescale #eligble voters in THSD
	replace wahlber_gesamt = wahlber_gesamt/1000 
	// rescale turnout [0-100]
	foreach v of varlist sbez_turnout* {
		replace `v' = `v' * 100
	}	
	// gen: Share of in-person votes OHNE Wahlschein in total votes (not requested!)
	gen shr_urne = 100*(sbez_turnout_urne_ohne / sbez_turnout_tot)
	
	//  variables for stats
	gen shr_urne_mit_all =  100*(sbez_turnout_urne_mit / sbez_turnout_tot) // shr of poll voters w polling card in all votes
	gen shr_compl_urne = 100*(sbez_turnout_urne_mit / sbez_turnout_pos_req) // shr of poll voters w polling card in all EV w polling card
	gen shr_compl_pos =	100*(sbez_turnout_pos / sbez_turnout_pos_req) // shr of mail voters in all EV w polling card
	gen shr_compl_tot = 100*((sbez_turnout_pos + sbez_turnout_urne_mit) / sbez_turnout_pos_req) // shr of mail and poll voters w polling card in all voters w PC
	gen shr_urne_mit =  100*(sbez_turnout_urne_mit / (sbez_turnout_pos + sbez_turnout_urne_mit)) // shr of poll voters w PC in all votes w PC

	list wahl shr_* sbez_turnout_tot, abb(20)
	
	// ticks
	forvalues y = 2013/2020 {
		local jan `jan' `=mdy(1,1,`y')'
		local jul `jul' `=mdy(7,1,`y')'
	}
	local jan `jan' `=mdy(1,1,2021)'
	
	// adjust location of bars
	replace wahl_date = mdy(3,15,2013) if wahl == "LTW13"
	replace wahl_date = mdy(9,15,2013) if wahl == "BTW13"
	replace wahl_date = mdy(3,15,2014) if wahl == "KOW14"
	replace wahl_date = mdy(9,15,2014) if wahl == "EUW14"
	replace wahl_date = mdy(7,1,2017) if wahl == "BTW17"
	replace wahl_date = mdy(7,1,2018) if wahl == "LTW18"
	replace wahl_date = mdy(7,1,2019) if wahl == "EUW19"
	replace wahl_date = mdy(7,1,2020) if wahl == "KOW20"
	
	// set barwidth
	local barwidth 100
	local tmp = `barwidth'/2
	
	// prep for fill pattern
	expand 3 if wahl_type == 2, gen(exp)
	replace wahl_type = . if exp == 1
	bys wahl exp: replace wahl_date = wahl_date - `tmp' if exp ==1 & _n == 1
	bys wahl exp (wahl_date): replace wahl_date = wahl_date + `tmp' if exp ==1 & _n == _N
	
	sort wahl_date

	* PLOT: FIGURE 1. Timeline and Turnout of Elections Held between 2013 and 2020
	tw  (bar wahlber_gesamt wahl_date if wahl_type == 1, yaxis(1) yscale(r(0) axis(1)) ylabel(0(200)1200) barwidth(`barwidth') fcolor(white) lcol(black)) ///
		(bar wahlber_gesamt wahl_date if wahl_type == 2, yaxis(1) yscale(r(0) axis(1)) ylabel(0(200)1200) barwidth(`barwidth') fcolor("scheme p6") lcol(black))  ///
		(bar wahlber_gesamt wahl_date if wahl_type == 3, yaxis(1) yscale(r(0) axis(1)) ylabel(0(200)1200) barwidth(`barwidth') fcolor("scheme p8") lcol(black)) ///
		(bar wahlber_gesamt wahl_date if wahl_type == 4, yaxis(1) yscale(r(0) axis(1)) ylabel(0(200)1200) barwidth(`barwidth') fcolor("scheme p1") lcol(black)) ///
		(scatter sbez_turnout_tot wahl_date if exp == 0, yaxis(2) ms(t) mcol(black) msize(large) yscale(r(0) axis(2)) ylabel(0(20)100, axis(2))) ///
		(line shr_urne wahl_date if exp == 0, yaxis(2) lpattern(solid) lcol(black)) ///
		(scatter shr_urne wahl_date if exp == 0, yaxis(2) ms(x) mcol(black)) ///
	,  ytitle("Eligible voters (thsd)", axis(1)) ytitle("Percent", axis(2)) xtitle("") ylab(, nogrid) xlab(,nogrid) ///
	 legend(lab(1 "Federal Election") lab(2 "European Election") lab(3 "Municipal Election") ///
		lab(4 "State Election") lab(5 "Total turnout") lab(6 "Share of polling place votes") pos(6) order(1 2 3 4 5 6) cols(2) rows(3)) ///
		xlabel(`jul',format(%tdCY) noticks) xtick(`jan') aspect(.6)
	
	graph export "$figures/Figure_1_wahlber_turnout_over_time.pdf", replace
}


* PLOT: Treatment Timing at the Precinct level: TREATMENT = 100% reassigned
	cap drop tmp*
	cap drop _*
	
	bys sb_new: egen tmp_cnt = total(fulltreat_simple)
	
	// sort precincts by never-treated > most frequently treated
	egen tmp_id = group(sb_new)
	
	gen 	tmp_bi_treat = fulltreat_simple
	
	* PLOT: FIGURE D.6 Timing of Polling Place Reassignments
	// heatplot
	heatplot tmp_bi_treat i.tmp_id i.wahl_id,  colors(black%2 navy) ///
	ylab(0(40)620, labsize(vsmall) nogrid) ysc(r(1,618)) xlab(1 `" "State" "2013" "' 2 `" "Federal" "2013" "' ///
		3 `" "Municipal" "2014" "' 4 `" "European" "2014" "' 5 `" "Federal" "2017" "' ///
		6 `" "State" "2018" "' 7 `" "European" "2019" "' 8 `" "Municipal" "2020" "',labsize(2.7pt)  nogrid) ///
	ytitle("Precinct ID") xtitle("Election")  discrete  statistic(asis) ///
	aspect(.6) xsc(titlegap(large)) levels(2) legend(pos(6))
	
	gr_edit .legend.subtitle.text = {}
	gr_edit .legend.subtitle.text.Arrpush "Full precinct reassigned"
	gr_edit .legend.plotregion1.label[1].text = {}
	gr_edit .legend.plotregion1.label[1].text.Arrpush 1
	gr_edit .legend.plotregion1.label[2].text = {}
	gr_edit .legend.plotregion1.label[2].text.Arrpush 0
	gr_edit .legend.plotregion1.DragBy 4 -21.5
	gr_edit .legend.plotregion1.label[1].text = {}
	gr_edit .legend.plotregion1.label[2].text = {}
	gr_edit .legend.plotregion1.key[2].view.style.editstyle area(shadestyle(intensity(0))) editcopy
	gr_edit .legend.plotregion1.key[2].view.style.editstyle area(linestyle(color("%0"))) editcopy
	gr_edit .legend.plotregion1.key[2].view.style.editstyle area(shadestyle(color("%0"))) editcopy
	gr_edit .legend.plotregion1.key[1].DragBy -0.15 0
	gr_edit .legend.yoffset = 4
	graph export "$figures/Figure_D6_heatmap_reassigned_bi.pdf", replace		


			
* Distribution of # times precinct treated repeatedly over time?				
	cap drop tmp*
	bys sb_new: egen tmp_tot_parttreat = total(parttreat_simple)
	bys sb_new: egen tmp_tot_fulltreat = total(fulltreat_simple)
	
  // For: treatment=100% reassigned (FIGURE D.6)
	tab tmp_tot_fulltreat if wahl_id==8 // 338 Never-treated units
										// 280 precincts treated at least once										
										
/* FIGURE D.6
tmp_tot_ful |
     ltreat |      Freq.     Percent        Cum.
------------+-----------------------------------
          0 |        338       54.69       54.69
          1 |        150       24.27       78.96
          2 |        106       17.15       96.12
          3 |         22        3.56       99.68
          4 |          1        0.16       99.84
          5 |          1        0.16      100.00
------------+-----------------------------------
      Total |        618      100.00
*/
										
	tab Ei if wahl_id==1		// 61.79 % first treated in BTW 2017
	/* FIGURE D.6
	       Ei    |      Freq.     Percent        Cum.
-----------------+-----------------------------------
    State (2013) |         10        3.57        3.57
Municipal (2014) |         10        3.57        7.14
  Federal (2017) |        173       61.79       68.93
    State (2018) |         35       12.50       81.43
 European (2019) |         12        4.29       85.71
Municipal (2020) |         40       14.29      100.00
-----------------+-----------------------------------
           Total |        280      100.00
	*/
	
	// in 39.8% of all instances in which treat_simple>0, reassigned = 100%	
		su parttreat_simple
		local pt = r(sum)
		su fulltreat_simple
		local ft = r(sum)
		di `ft'/`pt'

* Density plot of treatment intensity																				
	tabstat parttreat_simple fulltreat_simple, by(wahl_id)
	
	cap drop a50_simple
	gen 	a50_simple = (treat_simple >=0.5)
	
	su 		parttreat_simple
	local 	ps = r(sum)
	su 		fulltreat_simple
	local 	shr_full = (r(sum)/`ps')*100
	su 		a50_simple
	local 	shr_50= (r(sum)/`ps')*100
	su 		parttreat_consol
	local 	ps = r(sum)	
	su 		fulltreat_consol
	local   shr_full_cons = (r(sum)/`ps')*100
	su 		parttreat_no_consol
	local 	ps = r(sum)	
	su 		fulltreat_no_consol
	local   shr_full_no = (r(sum)/`ps')*100	
	di "`:di %12.2f `shr_full'' % of instances where treat_simple>0 are 100% reassinged" // 41% (K100 full)
	di "`:di %12.2f `shr_50'' % of instances where treat_simple>0 are 50% reassigned" // 61% (K50)
	di "`:di %12.2f `shr_full_cons'' % of instances where treat_consol>0 are 100% reassinged" // 16% (K100 consol)
	di "`:di %12.2f `shr_full_no'' % of instances where treat_no_consol>0 are 100% reassigned" // 54%	 (K100 no_consol)
	
	
	* PLOT: FIGURE D.5 Reassignment Intensity at the Precinct Level
	// Density Plot: treat_simple (all types of reassignments)
	tw (hist treat_simple if treat_simple >0, percent fcol(%0)), ///
		 xtitle("Share of reassigned addresses") ytitle("Percent")  ///
		title("Total")  legend(off) name(total, replace)  nodraw aspect(.7) 
	
	// Density: treat_consol (precinct reconfiguration)
	tw (hist treat_consol if parttreat_consol==1, percent fcol(%0)),  ///
		xtitle("Share of reassigned addresses") ytitle("Percent") ///
		title("Precinct reconfiguration") legend(off) name(consol, replace) nodraw aspect(.7)
	
	// Density: treat_no_consol (recruitment)
	tw (hist treat_no_consol if parttreat_no_consol==1, percent fcol(%0)),  ///
		xtitle("Share of reassigned addresses") ytitle("Percent") legend(off) ///
		title("Recruitment of different venue") name(no_consol, replace) nodraw aspect(.7)

	// combine and save
	graph combine total no_consol consol,  ycommon xcommon row(1) imargin(zero)
	graph export "$figures/Figure_D5_sb_treat_intensity.pdf", replace
